/**
 * Created by ZT on 2018/8/24 0024.
 */
/*文章接口*/
const sqls = require('../sqlMap');  //对应的mysql语句
const query = require('../db');
const mysql = require('mysql');
/**    
 *   前 台 文 章
 *      articlePersonal    获取专栏信息 
 *      getRight   右边信息
 *      getArticleTop  top为1的信息  一直存在
*/
/*获取文章信息*/
exports.getArticles=(req,res,next)=>{
    //type为1 所有，为2单条详细
    //加入數據庫
    let params = req.query;
       if(params['type']==1){
           let sqlParamsEntity = [];
           let page = params['page'];
           let per_page = params['per_page'];
           var startLimit = (page-1)*per_page;
           var limit =`${startLimit},${per_page}`;
           let sql1 = `select a.id,a.key,a.abstr,a.imgUrl,a.create_time,a.title,a.see,b.likes from
                       (select a.id,a.key,a.imgUrl,a.abstr,a.create_time,a.title,count(s.see) see from zt_article a 
                       left join zt_see s on a.id = s.article_id group by a.id) a
                         inner join
                        (select a.id,a.key,a.imgUrl,a.abstr,a.create_time,a.title,count(l.like_count) likes from zt_article a 
                       left join zt_like l on a.id = l.article_id group by a.id) b
                         on a.id = b.id limit ${limit};`;
           let sql2 = sqls.countTableLen('zt_article', '');
           sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
           sqlParamsEntity.push(query.getNewSqlParamEntity(sql2, {}));
           query.execTrans(sqlParamsEntity, function (err, result) {
               let results = { 'ret': 1, 'rows': result[0], 'total': result[1][0]['count(1)'] };
               res.json(results);
           });
       }else{
           let id = params['id'];
          let _sql = sqls.findData('zt_see',`where ip=? and type=1 and article_id=?`);
           _sql =mysql.format(_sql,[query.getIp(req),id]);
           console.log(_sql,44);
          query.connect(_sql,function (err,result) {
              if(!err){
                  if(result.length<=0){
                      let _sql = sqls.insertTable('zt_see','article_id,ip,see,type,time',`${id},?,1,1,?`);
                      console.log(_sql,4444);
                       _sql =mysql.format(_sql,[query.getIp(req),new Date().Format()]);
                       console.log(_sql,555);
                      query.connect(_sql,function (err,result) {
                          let results={};
                          if(err){
                              results = { 'ret': 0, 'msg': '插入失败'};
                              
                              res.send(results);
                          }else {
                              let sqls1 =`select a.id,a.abstr,a.create_time,a.title,a.see,b.content from zt_article a
                                         left join zt_content b on b.id = a.article_id
                                            WHERE a.id=${id}`;
                               let sqls2 =`select count(see) see from zt_see where article_id = ${id} and type=1`;
                               let sqls3 =`select count(like_count) see from zt_like where article_id = ${id} and type=1`;
                              query.connect(sqls1,sqls2,sqls3,function (err,result) {
                                  let results={};
                                  if(err){
                                      results = { 'ret': 0, 'msg': '获取失败'};
                                      res.send(results);
                                  }else {
                        
                                      results = { 'ret': 1, 'rows': result};
                                      res.send(results);
                                  }

                              });
                          }

                      });
                  }else{
                      let results={};
                      if(err){
                          results = { 'ret': 0, 'msg': '插入失败'};
                          res.send(results);
                      }else {
                          let sqls1 =`select a.id,a.key,a.content,a.abstr,a.create_time,a.title,a.see,b.likes from
                                          (select a.id,a.key,a.abstr,h.content,a.create_time,a.title,count(s.see) see from zt_article a
                                          left join zt_content h on a.content_id = h.id
                                          left join zt_see s on a.id = s.article_id
                                            WHERE a.id=${id}
                                           group by a.id
                                           ) a
                                          inner join
                                          (select a.id,a.key,a.abstr,h.content,a.create_time,a.title,count(l.like_count) likes from zt_article a
                                            left join zt_content h on a.content_id = h.id
                                          left join zt_like l on a.id = l.article_id 
                                           WHERE a.id=${id}
                                          group by a.id) b
                                          on a.id = b.id`;
                          query.connect(sqls1,function (err,resultAll) {
                              let results={};
                              if(err){
                                  results = { 'ret': 0, 'msg': '获取失败'};
                                  res.send(results);
                              }else {
                                  results = { 'ret': 1, 'rows': resultAll};
                                  res.send(results);
                              }

                          });
                      }

                  }
              }
          });
       }

}




/*--------------------获取专栏信息*/
exports.articlePersonal=(req,res,next)=>{
    let params = req.query;
    let union = `left join zt_content as B on A.content_id=B.id left join zt_category as C on A.category_id=C.id where A.is_reprint=0  order by A.create_time desc`;
    let fields = 'A.id,B.content,A.title,A.abstr,C.type_name,A.imgUrl,A.create_time,A.top,A.`key`,A.key_value,A.subtitle,A.imgUrl';
    let sqlParamsEntity = [];
    let page = params['page'];
    let per_page = params['per_page'];
    let sql1 = sqls.coTableData('zt_article', union, fields, page, per_page);
    let sql2 = sqls.countTableLen('zt_article', '');
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql2, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        let results = { 'ret': 1, 'rows': result[0], 'total': result[1][0]['count(1)'] };
        res.send(results);
    });
}

//----------------------右边信息
exports.getRight=(req,res,next)=>{
    var sqlParamsEntity = [];
    var sql1 = sqls.countTableLen('zt_discuss_article', '');
    var sql2 = sqls.countTableLen('zt_discuss_photo', '');
    var sql3 = sqls.countTableLen('zt_article', '');
    var sql4 = sqls.coTotal('zt_visit');
    var sql5 = sqls.findData('zt_category');
    var sql6 = sqls.findData('zt_article', `where top BETWEEN 1 and 5`);
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql1, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql2, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql3, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql4, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql5, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(sql6, {}));
    query.execTrans(sqlParamsEntity, function (err, result) {
        if (err) {
            let results = { 'ret': 0, 'msg': '获取失败' };
            res.send(results);
        } else {
            let params = {};
            let results = { 'ret': 1, 'rows': result };
            res.send(results);
        }
    })
}

/**
 * top获取首页的第一条信息，显示top为1的
 */
exports.getArticleTop=(req,res,next)=>{
    let union = `left join zt_content as B on A.content_id=B.id left join zt_category as C on A.category_id=C.id where A.top=1`;
    let fields = 'A.id,B.content,A.title,A.abstr,C.type_name,A.imgUrl,A.create_time,A.top,A.`key`,A.key_value,A.subtitle,A.imgUrl';
    let sql1 = sqls.coTableData('zt_article', union, fields);
    let results ={};
    query.connect(sql1,function (err,result) {
        if(err){
            results = { 'ret': 0, 'msg': '获取失败'};
            res.send(results);
        }else {
            results = { 'ret': 1, 'rows': result};
            res.send(results);
        }
    })
}


/**
* 获取数上一篇和下一篇*
* */
exports.getUpAndDown=(req,res,next)=>{
    let id = req.query.id;
    let downId = parseInt(id)-1;
      let upId = parseInt(id)+1;
    let _sql = sqls.findData('zt_article','where ?? = ?');
    let _sql2 = sqls.findData('zt_article','where ?? = ?');
    _sql = mysql.format(_sql,['id',downId]);
    _sql2 = mysql.format(_sql2,['id',upId]);
    console.log(_sql,_sql2);
    let sqlParamsEntity = [];
    sqlParamsEntity.push(query.getNewSqlParamEntity(_sql, {}));
    sqlParamsEntity.push(query.getNewSqlParamEntity(_sql2, {}));
    query.execTrans(sqlParamsEntity,(err,result)=>{
        let results={};
          if(err){
              results = {ret:0,msg:'添加失败'};
              res.json(results);
          }else{
              results ={ret:1,rows:result};
              res.json(results);
          }
    })

}


/*获取标签信息*/
exports.getLinkContent=(req,res,next)=>{
    let params = req.query;
    let id = params['id'];
    let union = `left join zt_content as B on A.content_id=B.id 
                   left join zt_category as C on A.category_id=C.id
                   left join zt_like as D on D.article_id= B.id 
                  left join zt_see as E on E.article_id= B.id 
                    where A.category_id=${id} GROUP BY D.article_id,E.article_id`;
    let fields = 'A.id,B.content,A.title,A.abstr,C.type_name,A.create_time,A.top,A.`key`,A.key_value,A.subtitle,A.imgUrl,sum(D.like_count) as likes,sum(E.see) as see';
    let sql = sqls.fidDateFromTable('zt_article', id, union, fields);
    query.connect(sql,function (err,result) {
        let results={};
        if(err){
            results = { 'ret': 0, 'msg': '获取失败'};
            res.json(results);
        }else {
            results = { 'ret': 1, 'rows': result};
            res.json(results);
        }

    });
}

/*通过key查询*/
exports.getSearchKey=(req,res,next)=>{
    let params = req.query;
      let keywords = params['content'];
    let union = `left join zt_content as B on A.content_id=B.id 
                   left join zt_category as C on A.category_id=C.id
                   left join zt_like as D on D.article_id= B.id 
                  left join zt_see as E on E.article_id= B.id 
                    where B.content like '%${keywords}%' GROUP BY D.article_id,E.article_id`;
    let fields = 'A.id,B.content,A.title,A.abstr,C.type_name,A.create_time,A.top,A.`key`,A.key_value,A.subtitle,A.imgUrl,sum(D.like_count) as likes,sum(E.see) as see';
    let sql = sqls.fidDateFromTable('zt_article','id', union, fields);
    query.connect(sql,function (err,result) {
        let results={};
        if(err){
            results = { 'ret': 0, 'msg': '获取失败'};
            res.json(results);
        }else {
            results = { 'ret': 1, 'rows': result};
            res.json(results);
        }
    });
}


/**
 * 点赞
* **/
exports.likesThis=(req,res,next)=>{
    let params = req.query;
    let id = params['id'];
    let _sql = sqls.findData('zt_like',`where ip=? and type=1 and article_id=?`);
    _sql =mysql.format(_sql,[query.getIp(req),id]);
    let results = {};
    query.connect(_sql,function (err,result) {
        if (!err) {
            if (result.length <= 0) {
                let _sql = sqls.insertTable('zt_like', 'article_id,ip,like_count,type,time', `${id},?,1,1,?`);
                _sql = mysql.format(_sql, [query.getIp(req),new Date().Format()]);
                query.connect(_sql, function (err, result) {
                    if (!err) {
                        results = {'ret': 1, 'msg': '点赞成功','type':1};
                        res.send(results);
                    }
                });
            }else{
                results = {'ret': 1, 'msg': '您已点过赞啦','type':2};
                res.send(results);
            }
        }
    })
};